package com.example.thread.demo;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author void
 * @date 2021/8/12 16:12
 * @desc
 */
@Slf4j
public class Demo1 {

    public static void main(String[] args) {
        LinkedBlockingQueue<Long> blockingQueue = new LinkedBlockingQueue<>();
        for(long i=0;i<10000;i++){
            blockingQueue.add(i);
        }
        
        ThreadPoolExecutor es = new ThreadPoolExecutor(4, 4, 10L, TimeUnit.SECONDS, 
                new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("谷歌线程池-%d").build());
        es.submit(new BlockingRunHandler(blockingQueue));
        es.shutdown();
        try {
            while (!es.isTerminated()) {
                if (es.awaitTermination(5, TimeUnit.SECONDS)) {
                    log.info("线程池执行完成");
                } else {
                    log.info("线程池还在运行");
                }
            }
        } catch (InterruptedException ie) {
            es.shutdownNow();
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            es.shutdownNow();
        }
    }

    /**
     * @author void
     * @date 2021/8/12 16:22
     * @desc
     */
    @Slf4j
    public static class BlockingRunHandler implements Runnable{
    
        private LinkedBlockingQueue<Long> queue;
    
        public BlockingRunHandler(LinkedBlockingQueue<Long> queue) {
            this.queue = queue;
        }
    
        @Override
        public void run() {
            Long orderId;
            try{
                while ((orderId=queue.poll())!=null){
                    log.info("orderId:{}", orderId);
                }
                log.info("结束啦,orderId:{}", orderId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
